package com.example.book.api;

import com.example.book.base.ApiBaseController;
import com.example.book.base.Result;
import com.example.book.common.annotation.LoginIgnore;
import com.example.book.common.utils.Constants;
import com.example.book.common.utils.RedisService;
import com.example.book.domain.wx.UserInfo;
import com.example.book.in.entity.*;
import com.example.book.in.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.awt.print.Book;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/book")
public class ApiUserReadRecordController extends ApiBaseController {

    private UserReadRecordService userReadRecordService;
    private RedisService redisService;
    private BookInfoService bookInfoService;
    private BookCatalogService bookCatalogService;
    private BookPopularityService popularityService;
    private BookCategoryService bookCategoryService;


    private ApiUserReadRecordController(UserReadRecordService userReadRecordService, RedisService redisService, BookInfoService bookInfoService,
                                        BookCatalogService bookCatalogService, BookPopularityService popularityService, BookCategoryService bookCategoryService) {
        this.userReadRecordService = userReadRecordService;
        this.redisService = redisService;
        this.bookInfoService = bookInfoService;
        this.bookCatalogService = bookCatalogService;
        this.popularityService = popularityService;
        this.bookCategoryService = bookCategoryService;
    }


    /**
     * 首页四条用户阅读量最大的书籍
     *
     * @return
     */
    @GetMapping("/record/max")
    @LoginIgnore
    public Result findRecordMax() {

        Integer i = 5;
        //5条
        List<UserReadRecord> recordList = userReadRecordService.selectRecordDescLimit();

        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map = null;
        BookInfo bookInfo = new BookInfo();
        BookCategory category = new BookCategory();
        for (UserReadRecord urr : recordList) {
            bookInfo.setId(urr.getBookInfoId());
            BookInfo bi = bookInfoService.get(bookInfo);
            if (bi != null) {
                map = new HashMap<>();
                map.put("id", bi.getId());
                map.put("picture", picture_url + bi.getBookCover());

                if (bi.getBookName().length() > 15) {
                    String idt = bi.getBookName().substring(0, 15) + "...";
                    map.put("name", idt);
                } else {
                    map.put("name", bi.getBookName());
                }
                map.put("author", bi.getBookAuthor().replace("作者：", ""));

                category.setId(bi.getCategoryId());
                BookCategory bc = bookCategoryService.get(category);
                if (bc != null) {
                    map.put("category", bc.getName());
                } else {
                    map.put("category", "未分类");
                }

                // 人气
                BookPopularity bookPopularity = new BookPopularity();
                bookPopularity.setBookInfoId(bi.getId());
                List<BookPopularity> popularities = popularityService.findList(bookPopularity);
                map.put("popularity", popularities.size());

                if (bi.getBookIntroduction().length() > 46) {
                    String idt = bi.getBookIntroduction().substring(0, 46) + "...";
                    map.put("introduction", idt);
                } else {
                    if (StringUtils.isBlank(bi.getBookIntroduction())) {
                        map.put("introduction", "^^...");
                    } else {
                        map.put("introduction", bi.getBookIntroduction());
                    }
                }
            }
            list.add(map);
        }

        if (list.size() != i) {
            Integer limit = i - list.size();
            // 查询 设置热门搜索的数据
            List<BookInfo> bookInfos = bookInfoService.selectPopularSearches(limit);
            for (BookInfo info : bookInfos) {
                map = new HashMap<>();
                map.put("id", info.getId());
                map.put("picture", picture_url + info.getBookCover());

                if (info.getBookName().length() > 15) {
                    String idt = info.getBookName().substring(0, 15) + "...";
                    map.put("name", idt);
                } else {
                    map.put("name", info.getBookName());
                }
                map.put("author", info.getBookAuthor().replace("作者：", ""));

                // 人气
                BookPopularity bookPopularity = new BookPopularity();
                bookPopularity.setBookInfoId(info.getId());
                List<BookPopularity> popularities = popularityService.findList(bookPopularity);
                map.put("popularity", popularities.size());

                if (info.getBookIntroduction().length() > 46) {
                    String idt = info.getBookIntroduction().substring(0, 46) + "...";
                    map.put("introduction", idt);
                } else {
                    if (StringUtils.isBlank(info.getBookIntroduction())) {
                        map.put("introduction", "^^...");
                    } else {
                        map.put("introduction", info.getBookIntroduction());
                    }
                }
                list.add(map);
            }
        }

        map = new HashMap<>();

        map.put("maxRead", list.get(0));

        List<Map<String, Object>> list1 = new ArrayList<>();

        for (int j = 1; j < list.size(); j++) {
            list1.add(list.get(j));
        }
        map.put("maxList", list1);

        return Result.success(map);
    }

    /**
     * 获取用户阅读记录 最新的五条
     *
     * @param readRecord
     * @return
     */
    @GetMapping("/record/list")
    public Result recordList(UserReadRecord readRecord) {
        List<UserReadRecord> recordList = userReadRecordService.selectUserRecordLimit(readRecord);

        // 没有记录
        if (recordList.size() < 1) {
            return Result.error();
        }

        List<Map<String, Object>> maps = new ArrayList<>();
        Map<String, Object> map = null;
        BookInfo bookInfo = new BookInfo();
        for (UserReadRecord urr : recordList) {
            bookInfo.setId(urr.getBookInfoId());
            BookInfo bi = bookInfoService.get(bookInfo);
            if (bi != null) {
                map = new HashMap<>();
                map.put("id", bi.getId());
                map.put("picture", picture_url + bi.getBookCover());

                if (bi.getBookName().length() > 15) {
                    String idt = bi.getBookName().substring(0, 15) + "...";
                    map.put("name", idt);
                } else {
                    map.put("name", bi.getBookName());
                }
                map.put("author", bi.getBookAuthor().replace("作者：", ""));

                // 计算 阅读百分比 当前阅读数
                BookCatalog bc = new BookCatalog();
                bc.setId(urr.getBookCatalogId());
                BookCatalog current = bookCatalogService.get(bc);

                // 查询书籍目录 最后一章 的索引
                BookCatalog catalog = new BookCatalog();
                catalog.setBookInfoId(bi.getId());
                BookCatalog last = bookCatalogService.selectOrderByIndexDesc(catalog);

                BigDecimal bd = new BigDecimal(current.getCatalogIndex()).divide(new BigDecimal(last.getCatalogIndex()), 2, BigDecimal.ROUND_HALF_UP);

                map.put("percentage", bd);

                maps.add(map);
            }
        }

        if (maps.size() < 1) {
            return Result.error("no data");
        }
        return Result.success(maps);
    }

    /**
     * 生成用户阅读记录
     *
     * @param readRecord
     * @return
     */
    @PostMapping("/record")
    public Result createReadRecord(UserReadRecord readRecord) {

        String token = getToken();
        //用户没有登陆时不记录
        if (StringUtils.isBlank(token)) {
            return Result.error();
        }
        // 有token 没有用户时不记录
        UserInfo userInfo = (UserInfo) redisService.get(Constants.WX_API_TOKEN + token);
        if (userInfo == null) {
            return Result.error();
        }

        userReadRecordService.save(readRecord);

        return Result.success();
    }

}
